package com.zy.modules.sys.service.impl;

import com.zy.modules.sys.entity.SysRoleEntity;
import com.zy.modules.sys.repo.RoleRepository;
import com.zy.modules.sys.service.SysRoleMenuService;
import com.zy.modules.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 角色
 *
 *
 *
 * @date 2016年9月18日 上午9:45:12
 */
@Service("sysRoleService")
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private RoleRepository roleRepository;

    @Override
    public SysRoleEntity queryObject(Long roleId) {
        return roleRepository.findOne(roleId);
    }

    @Override
    public List<SysRoleEntity> queryList(Map<String, Object> map) {
        int limit = (int) map.getOrDefault("limit", 10);
        int offset = (int) map.getOrDefault("offset", 0);
        Pageable pageable = new PageRequest(offset, limit);
        Page<SysRoleEntity> entities = roleRepository.findAll(pageable);
        return entities.getContent();
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        long count = roleRepository.count();
        return (int) count;
    }

    @Override
    @Transactional
    public void save(SysRoleEntity role) {
        role.setCreateTime(new Date());
        roleRepository.save(role);

        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional
    public void update(SysRoleEntity role) {
        roleRepository.save(role);

        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional
    public void deleteBatch(Long[] roleIds) {
        for (Long roleId : roleIds) {
            roleRepository.delete(roleId);
        }
    }

}
